<template>
  <view class="count-box">
    <button @click="handleSub" class="minus">-</button>
    <input v-model="inputValue" class="inp" @change="handleChange" type="number" />
    <button @click="handleAdd" class="add">+</button>
  </view>
</template>

<script>
export default {
  name: 'count-box',
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      inputValue: this.value
    };
  },
  watch: {
    value(val) {
      this.inputValue = +val;
    }
  },
  methods: {
    handleSub() {
      if (this.value <= 1) {
        return;
      }
      this.$emit('input', this.value - 1);
    },
    handleAdd() {
      this.$emit('input', this.value + 1);
    },
    handleChange(e) {
      // console.log(e);
      // const num = +e.target.value;
      let num = parseInt(e.target.value);
      console.log(num);
      if (num < 0 || isNaN(num)) {
        // e.target.value = this.value;
        this.inputValue = 1;
        this.$emit('input', this.inputValue);
        return;
      }
      this.inputValue = num;
      this.$emit('input', this.inputValue);
    }
    // onBlur(e) {

    //   // 将用户输入的内容转化为整数
    //   let num = parseInt(e.target.value);
    //   if (!num) {
    //     this.inputValue=1
    //     return;
    //   }
    //   this.inputValue = +num;
    // }
  }
};
</script>

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;
  .add,
  .minus {
    padding: 0 0;
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #f1f1f1;
    text-align: center;
    line-height: 30px;
  }
  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #f1f1f1;
    text-align: center;
  }
}
</style>
